const api = require('../../../api/store_api');
import { toast, log, err, get } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    user: {},
  },
  onLoad() {
    this.setData({
      user: get('user'),
    });
  },
  async user() {
    try {
      const res = await api.getuser();
      if (res.respCode === 200) {
        const user = JSON.parse(res.source);
        this.setData({ user });
        wx.setStorageSync('user', user);
      }
    } catch (error) {
      err(error);
    }
  },
  putxgname() {
    try {
      wx.showModal({
        title: '修改昵称',
        editable: true,
        complete: async res => {
          if (res.confirm) {
            const data = {
              id: this.data.user.id,
              name: res.content,
            };
            const { respCode, msg } = await api.putuser(data);
            if (respCode === 200) {
              this.user();
              toast('修改成功');
            } else {
              toast(msg);
            }
          }
        },
      });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  xiu() {
    wx.showLoading({
      title: '修改中',
    });
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        this.compress_img(res.tempFiles[0].tempFilePath);
      },
      fail: err => {
        console.error(err);
        toast('上传失败');
        wx.hideLoading();
      },
    });
  },
  avatar(e) {
    wx.showLoading({
      title: '上传中',
    });
    let { avatarUrl } = e.detail;
    let timestamp = new Date().valueOf();
    wx.cloud.uploadFile({
      cloudPath: 'head_url/' + timestamp + '.jng',
      filePath: avatarUrl,
      success: async res => {
        const data = {
          id: this.data.user.id,
          avatarUrl: res.fileID,
        };
        const { respCode } = await api.putuser(data);
        if (respCode === 200) {
          toast('修改成功');
          this.user();
        }
      },
      fail: err => {
        console.log(err);
        toast('上传失败');
      },
    });
  },
  putphone() {
    wx.showModal({
      title: '修改手机号',
      editable: true,
      complete: res => {
        if (res.confirm) {
          let mobile = res.content;
          if (!/^1[34578]\d{9}$/.test(mobile)) {
            toast('手机号有误');
          } else {
            let data = {
              id: this.data.user.id,
              mobile,
            };
            api.putuser(data).then(res => {
              log(res);
              if (res.respCode === 200) {
                this.user();
                toast('修改成功');
              } else {
                toast(res.msg);
              }
            });
          }
        }
      },
    });
  },
});
